package com.biz.primus.ms.auth.dao.specification;

import com.biz.primus.model.sso.account.vo.UserReqVo;
import com.biz.primus.ms.auth.dao.po.User;
import com.google.common.collect.Lists;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

public class UserDynamicSpecification implements Specification<User> {

    private UserReqVo userReqVo;

    public UserDynamicSpecification(UserReqVo userReqVo) {
        this.userReqVo = userReqVo;
    }

    @Override
    public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = Lists.newArrayList();
        if (userReqVo.getStatus() != null) {
            Predicate predicate = criteriaBuilder.equal(root.get("status"), userReqVo.getStatus());
            predicates.add(predicate);
        }
        if (StringUtils.isNotBlank(userReqVo.getUserUnionId())) {
            String sqlUsername = "%" + userReqVo.getUserUnionId().trim() + "%";
            predicates.add(criteriaBuilder.like(root.get("userUnionId").as(String.class), sqlUsername));
        }
        if (userReqVo.getKeyword() != null) {
            String sqlKeyword = "%" + userReqVo.getKeyword().trim() + "%";
            predicates.add(criteriaBuilder.like(root.get("description").as(String.class), sqlKeyword));
        }
        criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
        return criteriaQuery.getRestriction();
    }
}